package com.evil.common.core.util;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 层级分类
 *
 * @author liyang
 * @date 2022-08-08 00:00
 */
public class ClassifyUtil {

    public static <T, U> List<T> classify(List<T> list, Function<T, U> getId, Function<T, U> getParentId, Comparator<T> comparator, BiConsumer<T, List<T>> setChildren, U root) {
        Map<U, List<T>> levelMap = list.stream().sorted(comparator).collect(Collectors.groupingBy(getParentId));
        Map<U, T> map = list.stream().filter(e -> !getId.apply(e).equals(root)).collect(StreamUtil.orderlyToMap(getId, e -> e));
        for (Map.Entry<U, List<T>> entry : levelMap.entrySet()) {
            if (map.containsKey(entry.getKey())) {
                setChildren.accept(map.get(entry.getKey()), entry.getValue());
            }
        }
        return levelMap.getOrDefault(root, new ArrayList<>());
    }
}
